package com.customization.unionpay.market.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.customization.unionpay.market.service.ClearFundDetailsButtonService;
import com.customization.unionpay.market.util.ClearFundButtonRelated;
import com.customization.unionpay.market.util.FormDataUtils;
import com.customization.unionpay.market.util.DailyReportRelated;
import com.customization.unionpay.market.util.PropUtils;
import com.engine.core.impl.Service;
import org.apache.commons.lang.StringUtils;
import weaver.hrm.User;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;

import java.math.BigDecimal;
import java.util.List;

public class ClearFundDetailsButtonServiceImpl extends Service implements ClearFundDetailsButtonService {

    private static final Logger log = LoggerFactory.getLogger(ClearFundDetailsButtonServiceImpl.class);

    @Override
    public void addOrUpdateInfo(int formId, int formmodeId, User user, String ywlx, String zjly, String qsrq, String sjly, String qsje) throws Exception {
        try {
            if (StrUtil.isNotBlank(ywlx) && StrUtil.isNotBlank(zjly) && StrUtil.isNotBlank(qsrq) && StrUtil.isNotBlank(sjly) && StrUtil.isNotBlank(qsje)) {
                if(ywlx.contains("消费")){
                    ywlx = "积分（消费送红包）";
                }else if(ywlx.contains("普通")){
                    ywlx = "积分（普通）";
                }else if(ywlx.contains("激励金")){
                    ywlx = "奖励金";
                }
                // 获取主表表名
                String maintablename = com.customization.unionpay.market.util.FormDataUtils.getTableName(formId);
                log.info("获取主表表名："+maintablename);
                List<JSONObject> lists = com.customization.unionpay.market.util.ClearFundButtonRelated.selectInfoBySth(maintablename, ywlx, zjly, qsrq, sjly);
                if (lists.size() > 0) {
                    // 修改
                    log.info("修改："+lists);

                    String id = lists.get(0).getString("id");
                    Double qsjeOldValue = "".equals(lists.get(0).getString("qsje")) ? 0 : new BigDecimal(lists.get(0).getString("qsje")).doubleValue();
                    Double qsjeNewValue = new BigDecimal(qsje).doubleValue();
                    String value = String.valueOf((qsjeOldValue+qsjeNewValue));
                    com.customization.unionpay.market.util.ClearFundButtonRelated.updateInfoById(maintablename, id, value);
                } else {
                    // 新增
                    log.info("新增");
                    com.customization.unionpay.market.util.ClearFundButtonRelated.addInfoByFormId(formId, formmodeId, maintablename, user, ywlx, zjly, qsrq, sjly, qsje);
                }
            } else {
                log.error("字段为空,请检查excel!");
                throw new Exception("字段为空,请检查excel!");
            }
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

    /**
     * 确认数据处理逻辑
     * @param ids
     * @param user
     */
    @Override
    public String comfirmDataAllInfo(String ids, User user) throws Exception {

        String result = null;

        // # 营销事项申请流程id
        String marketingApplicationWorkId = PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_application_work_id");

        // 清算资金汇总台账表单id
        int clearingFundSummaryLedgerFormId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "clearing_fund_summary_ledger_form_id"));

        // 营销活动日报表台账表单id
        int reportFormId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_activity_daily_report_form_id"));
        // 营销活动日报表台账模块id
        int reportFormModeId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_activity_daily_report_formmode_id"));

        // 清算资金明细台账表单id
        int clearingFundDetailsLedgerFormId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "clearing_fund_details_ledger_form_id"));

        // 营销活动事项台账表单id
        int formId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_activity_ledger_form_id"));

        // 查询枚举 日报流水类型 正常数据
        String rblslxNormalData = com.customization.unionpay.market.util.FormDataUtils.getItemValue(reportFormId, "rblslx", "正常数据");
        log.info("正常数据枚举值："+rblslxNormalData);
        // 查询枚举 日报流水类型 异常数据
        String rblslxErrorData = com.customization.unionpay.market.util.FormDataUtils.getItemValue(reportFormId, "rblslx", "异常数据");
        log.info("异常数据枚举值："+rblslxErrorData);
        // 查询枚举 日报流水类型 异常数据
        String rblslxEndData = com.customization.unionpay.market.util.FormDataUtils.getItemValue(reportFormId, "rblslx", "活动结束后交易数据");
        log.info("活动结束后交易数据枚举值："+rblslxEndData);

        String isConfirmAll = com.customization.unionpay.market.util.FormDataUtils.getItemValue(clearingFundSummaryLedgerFormId, "zt", "已确认未入账");
        log.info("已确认未入账汇总枚举值："+isConfirmAll);
        String isConfirmDetail = com.customization.unionpay.market.util.FormDataUtils.getItemValue(clearingFundDetailsLedgerFormId, "zt", "已确认未入账");
        log.info("已确认未入账明细枚举值："+isConfirmDetail);

        String clearingFundDetailTableName = com.customization.unionpay.market.util.FormDataUtils.getTableName(clearingFundDetailsLedgerFormId);
        log.info("clearingFundDetailTableName："+clearingFundDetailTableName);
        String clearingFundSummaryTableName = com.customization.unionpay.market.util.FormDataUtils.getTableName(clearingFundSummaryLedgerFormId);
        log.info("clearingFundSummaryTableName："+clearingFundSummaryTableName);
        String marketingActivityLedgerTableName = com.customization.unionpay.market.util.FormDataUtils.getTableName(formId);
        log.info("marketingActivityLedgerTableName："+marketingActivityLedgerTableName);
        String reportTableName = com.customization.unionpay.market.util.FormDataUtils.getTableName(reportFormId);
        log.info("reportTableName："+reportTableName);

        String rblslxReal = rblslxNormalData;
        List<JSONObject> chooseFormData = com.customization.unionpay.market.util.ClearFundButtonRelated.getClearFundAllById(clearingFundSummaryTableName, ids);
        log.info("chooseFormData："+chooseFormData);

        String reson = "";

        // 汇总台账，需要查询明细
        for (JSONObject chooseData : chooseFormData) {
            Integer billid = chooseData.getInteger("id");
            //  业务类型        ywlx
            String ywlxR = chooseData.getString("ywlx");
            log.info("ywlxR:"+ywlxR);
            //  资金来源        zjly
            String zjly = chooseData.getString("zjly");
            log.info("zjly:"+zjly);
            //  清算日期        qsrq
            String qsrq = chooseData.getString("qsrq");
            log.info("qsrq:"+qsrq);
            //  数据来源        sjly
            String sjly = chooseData.getString("sjly");
            log.info("sjly:"+sjly);

            String ywlxC = ywlxR.replaceAll("新","");
            String likeValue = "立减";
            if(ywlxC.contains("消费")){
                ywlxC = "积分（消费送红包）";
                likeValue = "消费";
            }else if(ywlxC.contains("普通")){
                ywlxC = "积分（普通）";
                likeValue = "普通";
            }else if(ywlxC.contains("激励金")){
                ywlxC = "奖励金";
                likeValue = "激励金";
            }

            log.info("ywlxC:"+ywlxC);
            log.info("likeValue:"+likeValue);

            String actTp = com.customization.unionpay.market.util.FormDataUtils.getItemValue(reportFormId, "ACT_TP", ywlxC);

            String zjlyDetails = com.customization.unionpay.market.util.FormDataUtils.getItemName(clearingFundSummaryLedgerFormId, "zjly", zjly);
            String sjlyDetails = com.customization.unionpay.market.util.FormDataUtils.getItemName(clearingFundSummaryLedgerFormId, "sjly", sjly);

            String detailsTitle = "【"+ywlxR + zjlyDetails + qsrq + sjlyDetails+"】";
            log.info("detailsTitle:"+detailsTitle);
            //  状态            zt
            String ztAll = chooseData.getString("zt");
            if (!isConfirmAll.equals(ztAll)) {
                if (clearingFundDetailTableName != null && !"".equals(clearingFundDetailTableName)) {
                    // 查询清算资金明细台账
                    List<JSONObject> clearFundDetails = com.customization.unionpay.market.util.ClearFundButtonRelated.getClearFundDetailsByClearFundAllParams(clearingFundDetailTableName, likeValue, zjly, qsrq, sjly);
                    log.info("clearFundDetails:"+clearFundDetails);
                    if(clearFundDetails.size() > 0){
                        for (JSONObject clearFundDetail : clearFundDetails) {
                            try {
                                String ztDetail = clearFundDetail.getString("zt");
                                if (!isConfirmDetail.equals(ztDetail)) {
                                    String id = clearFundDetail.getString("id");
                                    String yxpthdsqm = clearFundDetail.getString("yxpthdsqm");
                                    String actNm = clearFundDetail.getString("act_nm");
                                    String actTotalAt = clearFundDetail.getString("act_total_at");
                                    String ptqdrq = clearFundDetail.getString("ptqdrq");
                                    String jbr = clearFundDetail.getString("jbr");
                                    String zbdw = clearFundDetail.getString("zbdw");
                                    String qsje = clearFundDetail.getString("qsje");
                                    String hdjsbs = StringUtils.isNotBlank(clearFundDetail.getString("hdjsbs")) ? clearFundDetail.getString("hdjsbs") : "否";

                                    // TODO 同步资金账户类型
                                    String zjzhlx = clearFundDetail.getString("zjzhlx");

                                    Double qsjeDb = Double.parseDouble(clearFundDetail.getString("qsje"));
                                    log.info("qsjeDb:"+qsjeDb);
                                    if (yxpthdsqm != null && !"".equals(yxpthdsqm)) {
                                        if (marketingActivityLedgerTableName != null && !"".equals(marketingActivityLedgerTableName)) {
                                            JSONObject marketingApplicantInfoByCode = com.customization.unionpay.market.util.ClearFundButtonRelated.getMarketingApplicantInfoByCode(marketingApplicationWorkId, marketingActivityLedgerTableName, yxpthdsqm);
                                            log.info("获取营销事项申请单数据：" + marketingApplicantInfoByCode);
                                            // ② 根据授权码(活动码)匹配财务系统对应SQ事项申请单，如果找不到该授权码对应SQ事项申请单，视为异常数据标记【日报流水类型】为“异常数据”;
                                            try {
                                                if (marketingApplicantInfoByCode != null) {
                                                    String zjlyAp = marketingApplicantInfoByCode.getString("zjly");
                                                    log.info("zjlyAp:"+zjlyAp);
                                                    String bdh = marketingApplicantInfoByCode.getString("bdh");
                                                    String nbczjehj = marketingApplicantInfoByCode.getString("nbczjehj");
                                                    String cwsfjs = marketingApplicantInfoByCode.getString("cwsfjs");
                                                    log.info("cwsfjs:"+cwsfjs);
                                                    String nbsybl = marketingApplicantInfoByCode.getString("nbsybl");
                                                    String ysyje = marketingApplicantInfoByCode.getString("ysyje");
                                                    log.info("ysyje:"+ysyje);
                                                    log.info("hdjsbs:"+hdjsbs);
                                                    if (!"是".equals(hdjsbs)) {
                                                        // ③ 如果找到对应SQ事项申请单，校验授权码尾号数字是否与申请单表头“资金来源”一致，如若不一致，视为异常数据标记【日报流水类型】为“异常数据”;
                                                        boolean b = com.customization.unionpay.market.util.ClearFundButtonRelated.compareToAuthCode(yxpthdsqm, zjlyAp, marketingApplicationWorkId);
                                                        log.info("b:"+b);
                                                        if (!b) {
                                                            rblslxReal = rblslxErrorData;
                                                            reson = "授权码尾号数字与申请单表头资金来源不一致属于异常数据";

//                                                            log.info("rblslxReal:"+rblslxReal);
//                                                            DailyReportRelated.addDailyReportData(reportFormId, reportFormModeId, user, reportTableName, yxpthdsqm, act_nm, act_total_at, ptqdrq, jbr, zbdw, qsje, actTp, zjly, qsrq, sjly, nbsybl, bdh, rblslxReal, isConfirmDetail,reson,zjzhlx);
                                                        }else {
                                                            // ④ 如果对应SQ事项申请单“财务处理结束”为“是”，财务处理已结束，该行正数数据也视为异常数据标记【日报流水类型】为“异常数据”； 负数清算数据标记【日报流水类型】为“活动结束后交易数据”；
                                                            if(cwsfjs != null && !"".equals(cwsfjs)){
                                                                String cwsfjsName = com.customization.unionpay.market.util.FormDataUtils.getItemName(formId, "cwsfjs", cwsfjs);
                                                                log.info("cwsfjsName:"+cwsfjsName);
                                                                if ("是".equals(cwsfjsName)) {
//                                                                    rblslxReal = rblslxEndData;
                                                                    if (qsjeDb > 0) {
                                                                        rblslxReal = rblslxErrorData;
                                                                        reson = "SQ事项申请单财务处理结束为是，请款金额为正数属于异常数据";
                                                                    } else {
                                                                        rblslxReal = rblslxEndData;
                                                                        reson = "";
                                                                    }
                                                                    log.info("rblslxReal:"+rblslxReal);
                                                                }else {
                                                                    String typeName = com.customization.unionpay.market.util.ClearFundButtonRelated.getTypeName(zjlyAp, marketingApplicationWorkId);
                                                                    log.info("typeName:"+typeName);
                                                                    log.info("ysyje:"+ysyje);
                                                                    if(ysyje != null && !"".equals(ysyje)){
                                                                        Double hj = Double.valueOf(nbczjehj);
                                                                        Double ysy = Double.valueOf(ysyje);
                                                                        if ("内部营销".equals(typeName)) {
                                                                            // ⑤ 如果对应SQ事项申请单“资金来源”为“内部”，“预算授权码”累计已使用金额大于对应SQ事项申请单“内部出资金额”；如超出，本次数据视为标记【日报流水类型】为“异常数据”；
                                                                            if (ysy > hj) {
                                                                                rblslxReal = rblslxErrorData;
                                                                                reson = "SQ事项申请单资金来源为内部，预算授权码累计已使用金额大于对应SQ事项申请单内部出资金额属于异常数据";
                                                                            }
                                                                        } else if ("内外部联合营销".equals(typeName)) {
                                                                            // ⑥ 如果对应SQ事项申请单“资金来源”为“内外部联合”，且累计已使用金额大于SQ事项申请单“内部出资金额”，视为异常数据标记【日报流水类型】为“异常数据”，则该行数据只允许导入和确认，不能入账。（临界值：按剩余内部出资金额入账）
                                                                            if (ysy > hj) {
                                                                                rblslxReal = rblslxErrorData;
                                                                                reson = "SQ事项申请单资金来源为资金来源，预算授权码累计已使用金额大于对应SQ事项申请单内部出资金额属于异常数据";
                                                                            }
                                                                        }
                                                                    }
                                                                }

//                                                                log.info("rblslxReal:"+rblslxReal);
//                                                                DailyReportRelated.addDailyReportData(reportFormId, reportFormModeId, user, reportTableName, yxpthdsqm, act_nm, act_total_at, ptqdrq, jbr, zbdw, qsje, actTp, zjly, qsrq, sjly, nbsybl, bdh, rblslxReal, isConfirmDetail,reson,zjzhlx);

                                                            }else {
                                                                String typeName = com.customization.unionpay.market.util.ClearFundButtonRelated.getTypeName(zjlyAp, marketingApplicationWorkId);
                                                                log.info("typeName:"+typeName);
                                                                log.info("ysyje:"+ysyje);
                                                                if(ysyje != null && !"".equals(ysyje)){
                                                                    Double hj = Double.valueOf(nbczjehj);
                                                                    Double ysy = Double.valueOf(ysyje);
                                                                    if ("内部营销".equals(typeName)) {
                                                                        // ⑤ 如果对应SQ事项申请单“资金来源”为“内部”，“预算授权码”累计已使用金额大于对应SQ事项申请单“内部出资金额”；如超出，本次数据视为标记【日报流水类型】为“异常数据”；
                                                                        if (ysy > hj) {
                                                                            rblslxReal = rblslxErrorData;
                                                                            reson = "SQ事项申请单资金来源为内部，预算授权码累计已使用金额大于对应SQ事项申请单内部出资金额属于异常数据";
                                                                        }
                                                                    } else if ("内外部联合营销".equals(typeName)) {
                                                                        // ⑥ 如果对应SQ事项申请单“资金来源”为“内外部联合”，且累计已使用金额大于SQ事项申请单“内部出资金额”，视为异常数据标记【日报流水类型】为“异常数据”，则该行数据只允许导入和确认，不能入账。（临界值：按剩余内部出资金额入账）
                                                                        if (ysy > hj) {
                                                                            rblslxReal = rblslxErrorData;
                                                                            reson = "SQ事项申请单资金来源为资金来源，预算授权码累计已使用金额大于对应SQ事项申请单内部出资金额属于异常数据";
                                                                        }
                                                                    }
                                                                }
//
//                                                                log.info("rblslxReal:"+rblslxReal);
//                                                                DailyReportRelated.addDailyReportData(reportFormId, reportFormModeId, user, reportTableName, yxpthdsqm, act_nm, act_total_at, ptqdrq, jbr, zbdw, qsje, actTp, zjly, qsrq, sjly, nbsybl, bdh, rblslxReal, isConfirmDetail,reson,zjzhlx);
                                                            }

                                                        }
                                                        log.info("rblslxReal:"+rblslxReal);
                                                        DailyReportRelated.addDailyReportData(reportFormId, reportFormModeId, user, reportTableName, yxpthdsqm, actNm, actTotalAt, ptqdrq, jbr, zbdw, qsje, actTp, zjly, qsrq, sjly, nbsybl, bdh, rblslxReal, isConfirmDetail,reson,zjzhlx,hdjsbs);
                                                    } else {
                                                        // ① 若活动已结束，本次获取数据都视为活动结束后交易数据，其中正数标记【日报流水类型】为“异常数据”，负数标记【日报流水类型】为“活动结束后交易数据”；
                                                        log.info("该条清算资金明细数据活动已结束");
                                                        if (qsjeDb > 0) {
                                                            rblslxReal = rblslxErrorData;
                                                            reson = "SQ事项申请单活动结束标识为是，请款金额为正数属于异常数据";
                                                        } else {
                                                            rblslxReal = rblslxEndData;
                                                            reson = "";
                                                        }
                                                        log.info("rblslxReal:"+rblslxReal);
                                                        DailyReportRelated.addDailyReportData(reportFormId, reportFormModeId, user, reportTableName, yxpthdsqm, actNm, actTotalAt, ptqdrq, jbr, zbdw, qsje, actTp, zjly, qsrq, sjly, nbsybl, bdh, rblslxReal, isConfirmDetail,reson,zjzhlx,hdjsbs);
                                                    }
                                                } else {
                                                    rblslxReal = rblslxErrorData;
                                                    log.info("rblslxReal:"+rblslxReal);
                                                    reson = "找不到该授权码对应SQ事项申请单";
                                                    DailyReportRelated.addDailyReportData(reportFormId, reportFormModeId, user, reportTableName, yxpthdsqm, actNm, actTotalAt, ptqdrq, jbr, zbdw, qsje, actTp, zjly, qsrq, sjly, "0", "", rblslxReal, isConfirmDetail,reson,zjzhlx,hdjsbs);
                                                }
                                                // 修改明细表状态
                                                com.customization.unionpay.market.util.ClearFundButtonRelated.updateStateByBillId(clearingFundDetailTableName, isConfirmDetail, Integer.parseInt(id));
                                            } catch (Exception e) {
                                                log.error("解析保存数据异常：" + e.getMessage());
                                                throw new Exception("解析保存数据异常：" + e.getMessage());
                                            }
                                        } else {
                                            log.error("营销活动事项台账表名为空！");
                                            throw new Exception("营销活动事项台账表名为空！");
                                        }
                                    } else {
                                        log.error("授权码为空!");
                                        if(result != null){
                                            result += ","+"清算资金明细数据id:"+id+"的营销平台活动授权码为空！";
                                        }else {
                                            result = "";
                                            result += "清算资金明细数据id:"+id+"的营销平台活动授权码为空！";
                                        }
                                    }
                                } else {
                                    log.info("该条清算资金明细数据已确认");
                                    if(result != null){
                                        result += ","+detailsTitle+"清算资金明细维度数据已确认";
                                    }else {
                                        result = "";
                                        result += detailsTitle+"清算资金明细维度数据已确认";
                                    }
                                }
                            } catch (Exception e) {
                                log.info("获取清算资金明细数据异常：" + e.getMessage());
                                throw new Exception("获取清算资金明细数据异常：" + e.getMessage());
                            }
                        }
                        // 修改汇总表状态
                        com.customization.unionpay.market.util.ClearFundButtonRelated.updateStateByBillId(clearingFundSummaryTableName, isConfirmAll, billid);
                    }else {
                        log.error("根据汇总类型查询清算资金明细台账数据为空！");
                    }
                } else {
                    log.error("查询清算资金明细台账表名为空！");
                }
            } else {
                // 按汇总规则已经【确认数据】写入《营销日报表台账》的明细数据，系统后台打上“已确认”标识，当用户重复操作汇总台账【确认数据】时提示“【业务类型+资金来源+清算日期+数据来源】该维度数据已确认”，此时系统控制不允许日报流水明细数据重复写入《营销日报表台账》。
                if(result != null){
                    result += ","+detailsTitle+"清算资金汇总维度数据已确认";
                }else {
                    result = "";
                    result += detailsTitle+"清算资金汇总维度数据已确认";
                }
            }
        }
        return result;
    }

    @Override
    public String comfirmDataDetailsInfo(String ids, User user) throws Exception {

        String result = null;

        // 营销事项申请流程id
        String marketingApplicationWorkId = PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_application_work_id");

        // 营销活动日报表台账表单id
        int reportFormId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_activity_daily_report_form_id"));
        // 营销活动日报表台账模块id
        int reportFormModeId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_activity_daily_report_formmode_id"));

        // 清算资金明细台账表单id
        int clearingFundDetailsLedgerFormId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "clearing_fund_details_ledger_form_id"));
        // 营销活动事项台账表单id
        int formId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_activity_ledger_form_id"));

        // 清算资金汇总台账表单id
        int clearingFundSummaryLedgerFormId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "clearing_fund_summary_ledger_form_id"));
        log.info("clearingFundSummaryLedgerFormId == >" +clearingFundSummaryLedgerFormId);
        // 清算资金汇总台账模块id
        int clearingFundSummaryLedgerFormmodeId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "clearing_fund_summary_ledger_formmode_id"));
        log.info("clearingFundSummaryLedgerFormmodeId == >" +clearingFundSummaryLedgerFormmodeId);

        ClearFundDetailsButtonServiceImpl clearFundDetailsButtonService = new ClearFundDetailsButtonServiceImpl();

        // 查询枚举 日报流水类型 正常数据
        String rblslxNormalData = com.customization.unionpay.market.util.FormDataUtils.getItemValue(reportFormId, "rblslx", "正常数据");
        log.info("正常数据枚举值："+rblslxNormalData);
        // 查询枚举 日报流水类型 异常数据
        String rblslxErrorData = com.customization.unionpay.market.util.FormDataUtils.getItemValue(reportFormId, "rblslx", "异常数据");
        log.info("异常数据枚举值："+rblslxErrorData);
        // 查询枚举 日报流水类型 异常数据
        String rblslxEndData = com.customization.unionpay.market.util.FormDataUtils.getItemValue(reportFormId, "rblslx", "活动结束后交易数据");
        log.info("活动结束后交易数据枚举值："+rblslxEndData);

        String isConfirmDetail = com.customization.unionpay.market.util.FormDataUtils.getItemValue(clearingFundDetailsLedgerFormId, "zt", "已确认未入账");
        log.info("已确认未入账枚举值："+isConfirmDetail);

        String clearingFundDetailTableName = com.customization.unionpay.market.util.FormDataUtils.getTableName(clearingFundDetailsLedgerFormId);
        log.info("clearingFundDetailTableName："+clearingFundDetailTableName);
        String marketingActivityLedgerTableName = com.customization.unionpay.market.util.FormDataUtils.getTableName(formId);
        log.info("marketingActivityLedgerTableName："+marketingActivityLedgerTableName);
        String reportTableName = com.customization.unionpay.market.util.FormDataUtils.getTableName(reportFormId);
        log.info("reportTableName："+reportTableName);

        String rblslxReal = rblslxNormalData;

        String reson = "";

        List<JSONObject> chooseFormData = com.customization.unionpay.market.util.ClearFundButtonRelated.getClearFundDetailsById(clearingFundDetailTableName, ids);
        // 明细台账，根据授权码查询申请单
        for (JSONObject chooseData : chooseFormData) {
            String ztDetail = chooseData.getString("zt");
            // 状态            zt
            Integer billid = chooseData.getInteger("id");
            //  业务类型        ywlx
            String ywlxR = chooseData.getString("ywlx");
            log.info("ywlxR:"+ywlxR);
            //  资金来源        zjly
            String zjly = chooseData.getString("zjly");
            log.info("zjly:"+zjly);
            //  清算日期        qsrq
            String qsrq = chooseData.getString("qsrq");
            log.info("qsrq:"+qsrq);
            //  数据来源        sjly
            String sjly = chooseData.getString("sjly");
            log.info("sjly:"+sjly);

            // TODO 同步资金账户类型
            String zjzhlx = chooseData.getString("zjzhlx");
            log.info("zjzhlx:"+zjzhlx);

            String ywlxC = ywlxR.replaceAll("新","");
            if(ywlxC.contains("消费")){
                ywlxC = "积分（消费送红包）";
            }else if(ywlxC.contains("普通")){
                ywlxC = "积分（普通）";
            }else if(ywlxC.contains("激励金")){
                ywlxC = "奖励金";
            }

            log.info("ywlxC:"+ywlxC);

            String actTp = com.customization.unionpay.market.util.FormDataUtils.getItemValue(reportFormId, "ACT_TP", ywlxC);

            String zjlyDetails = com.customization.unionpay.market.util.FormDataUtils.getItemName(clearingFundDetailsLedgerFormId, "zjly", zjly);
            String sjlyDetails = com.customization.unionpay.market.util.FormDataUtils.getItemName(clearingFundDetailsLedgerFormId, "sjly", sjly);

            String detailsTitle = "【"+ywlxR + zjlyDetails + qsrq + sjlyDetails+"】";
            log.info("detailsTitle:"+detailsTitle);

            if (!isConfirmDetail.equals(ztDetail)) {
                // 营销平台活动授权码 yxpthdsqm
                String yxpthdsqm = chooseData.getString("yxpthdsqm");
                // 活动名称         ACT_NM        act_nm
                String actNm = chooseData.getString("act_nm");
                // 活动金额         ACT_TOTAL_AT  act_total_at
                String actTotalAt = chooseData.getString("act_total_at");
                // 平台启动日期      ptqdrq
                String ptqdrq = chooseData.getString("ptqdrq");
                // 经办人          jbr
                String jbr = chooseData.getString("jbr");
                // 主办单位         zbdw
                String zbdw = chooseData.getString("zbdw");
                // 清算金额         qsje
                String qsje = chooseData.getString("qsje");
                // 活动结束标识      hdjsbs
                String hdjsbs = chooseData.getString("hdjsbs");

                Double qsjeDb = Double.parseDouble(qsje);
                log.info("qsjeDb:"+qsjeDb);
                if (yxpthdsqm != null && !"".equals(yxpthdsqm)) {
                    clearFundDetailsButtonService.addOrUpdateInfo(clearingFundSummaryLedgerFormId, clearingFundSummaryLedgerFormmodeId, user, ywlxC, zjly, qsrq, sjly, qsje);
                    if (marketingActivityLedgerTableName != null && !"".equals(marketingActivityLedgerTableName)) {
                        JSONObject marketingApplicantInfoByCode = com.customization.unionpay.market.util.ClearFundButtonRelated.getMarketingApplicantInfoByCode(marketingApplicationWorkId, marketingActivityLedgerTableName, yxpthdsqm);
                        log.info("获取营销事项申请单数据：" + marketingApplicantInfoByCode);
                        // ② 根据授权码(活动码)匹配财务系统对应SQ事项申请单，如果找不到该授权码对应SQ事项申请单，视为异常数据标记【日报流水类型】为“异常数据”;
                        try {
                            if (marketingApplicantInfoByCode != null) {
                                String zjlyAp = marketingApplicantInfoByCode.getString("zjly");
                                log.info("zjlyAp:"+zjlyAp);
                                String bdh = marketingApplicantInfoByCode.getString("bdh");
                                String nbczjehj = marketingApplicantInfoByCode.getString("nbczjehj");
                                String cwsfjs = marketingApplicantInfoByCode.getString("cwsfjs");
                                log.info("cwsfjs:"+cwsfjs);
                                String nbsybl = marketingApplicantInfoByCode.getString("nbsybl");
                                String ysyje = marketingApplicantInfoByCode.getString("ysyje");
                                log.info("ysyje:"+ysyje);
                                log.info("hdjsbs:"+hdjsbs);
                                if (!"是".equals(hdjsbs)) {
                                    // ③ 如果找到对应SQ事项申请单，校验授权码尾号数字是否与申请单表头“资金来源”一致，如若不一致，视为异常数据标记【日报流水类型】为“异常数据”;
                                    boolean b = com.customization.unionpay.market.util.ClearFundButtonRelated.compareToAuthCode(yxpthdsqm, zjlyAp, marketingApplicationWorkId);
                                    log.info("b:"+b);
                                    if (!b) {
                                        rblslxReal = rblslxErrorData;
                                        reson = "授权码尾号数字与申请单表头资金来源不一致属于异常数据";
//                                        log.info("rblslxReal:"+rblslxReal);
//                                        DailyReportRelated.addDailyReportData(reportFormId, reportFormModeId, user, reportTableName, yxpthdsqm, act_nm, act_total_at, ptqdrq, jbr, zbdw, qsje, actTp, zjly, qsrq, sjly, nbsybl, bdh, rblslxReal, isConfirmDetail,reson,zjzhlx);
                                    }else {
                                        if(cwsfjs != null && !"".equals(cwsfjs)) {
                                            // ④ 如果对应SQ事项申请单“财务处理结束”为“是”，财务处理已结束，该行正数数据也视为异常数据标记【日报流水类型】为“异常数据”；负数清算数据标记【日报流水类型】为“活动结束后交易数据”；
                                            String cwsfjsName = FormDataUtils.getItemName(formId, "cwsfjs", cwsfjs);
                                            log.info("cwsfjsName:" + cwsfjsName);
                                            if ("是".equals(cwsfjsName)) {
                                                if (qsjeDb > 0) {
                                                    rblslxReal = rblslxErrorData;
                                                    reson = "SQ事项申请单财务处理结束为是，请款金额为正数属于异常数据";
                                                } else {
                                                    rblslxReal = rblslxEndData;
                                                    reson = "";
                                                }
                                                log.info("rblslxReal:"+rblslxReal);
                                            } else {
                                                String typeName = com.customization.unionpay.market.util.ClearFundButtonRelated.getTypeName(zjlyAp, marketingApplicationWorkId);
                                                log.info("typeName:"+typeName);
                                                log.info("ysyje:"+ysyje);
                                                if(ysyje != null && !"".equals(ysyje)){
                                                    Double hj = Double.valueOf(nbczjehj);
                                                    Double ysy = Double.valueOf(ysyje);
                                                    if ("内部营销".equals(typeName)) {
                                                        // ⑤ 如果对应SQ事项申请单“资金来源”为“内部”，“预算授权码”累计已使用金额大于对应SQ事项申请单“内部出资金额”；如超出，本次数据视为标记【日报流水类型】为“异常数据”；
                                                        if (ysy > hj) {
                                                            rblslxReal = rblslxErrorData;
                                                            reson = "SQ事项申请单资金来源为内部，预算授权码累计已使用金额大于对应SQ事项申请单内部出资金额属于异常数据";
                                                        }
                                                    } else if ("内外部联合营销".equals(typeName)) {
                                                        // ⑥ 如果对应SQ事项申请单“资金来源”为“内外部联合”，且累计已使用金额大于SQ事项申请单“内部出资金额”，视为异常数据标记【日报流水类型】为“异常数据”，则该行数据只允许导入和确认，不能入账。（临界值：按剩余内部出资金额入账）
                                                        if (ysy > hj) {
                                                            rblslxReal = rblslxErrorData;
                                                            reson = "SQ事项申请单资金来源为资金来源，预算授权码累计已使用金额大于对应SQ事项申请单内部出资金额属于异常数据";
                                                        }
                                                    }
                                                }
                                            }
//                                            log.info("rblslxReal:"+rblslxReal);
//                                            DailyReportRelated.addDailyReportData(reportFormId, reportFormModeId, user, reportTableName, yxpthdsqm, act_nm, act_total_at, ptqdrq, jbr, zbdw, qsje, actTp, zjly, qsrq, sjly, nbsybl, bdh, rblslxReal, isConfirmDetail,reson,zjzhlx);
                                        }else {
                                            String typeName = com.customization.unionpay.market.util.ClearFundButtonRelated.getTypeName(zjlyAp, marketingApplicationWorkId);
                                            log.info("typeName:"+typeName);
                                            log.info("ysyje:"+ysyje);
                                            if(ysyje != null && !"".equals(ysyje)){
                                                Double hj = Double.valueOf(nbczjehj);
                                                Double ysy = Double.valueOf(ysyje);
                                                if ("内部营销".equals(typeName)) {
                                                    // ⑤ 如果对应SQ事项申请单“资金来源”为“内部”，“预算授权码”累计已使用金额大于对应SQ事项申请单“内部出资金额”；如超出，本次数据视为标记【日报流水类型】为“异常数据”；
                                                    if (ysy > hj) {
                                                        rblslxReal = rblslxErrorData;
                                                        reson = "SQ事项申请单资金来源为内部，预算授权码累计已使用金额大于对应SQ事项申请单内部出资金额属于异常数据";
                                                    }
                                                } else if ("内外部联合营销".equals(typeName)) {
                                                    // ⑥ 如果对应SQ事项申请单“资金来源”为“内外部联合”，且累计已使用金额大于SQ事项申请单“内部出资金额”，视为异常数据标记【日报流水类型】为“异常数据”，则该行数据只允许导入和确认，不能入账。（临界值：按剩余内部出资金额入账）
                                                    if (ysy > hj) {
                                                        rblslxReal = rblslxErrorData;
                                                        reson = "SQ事项申请单资金来源为资金来源，预算授权码累计已使用金额大于对应SQ事项申请单内部出资金额属于异常数据";
                                                    }
                                                }
                                            }
//                                            log.info("rblslxReal:"+rblslxReal);
//                                            DailyReportRelated.addDailyReportData(reportFormId, reportFormModeId, user, reportTableName, yxpthdsqm, act_nm, act_total_at, ptqdrq, jbr, zbdw, qsje, actTp, zjly, qsrq, sjly, nbsybl, bdh, rblslxReal, isConfirmDetail,reson,zjzhlx);
                                        }
                                    }
                                    log.info("rblslxReal:"+rblslxReal);
                                    DailyReportRelated.addDailyReportData(reportFormId, reportFormModeId, user, reportTableName, yxpthdsqm, actNm, actTotalAt, ptqdrq, jbr, zbdw, qsje, actTp, zjly, qsrq, sjly, nbsybl, bdh, rblslxReal, isConfirmDetail,reson,zjzhlx,hdjsbs);
                                } else {
                                    // ① 若活动已结束，本次获取数据都视为活动结束后交易数据，其中正数标记【日报流水类型】为“异常数据”，负数标记【日报流水类型】为“活动结束后交易数据”；
                                    log.info("该条清算资金明细数据活动已结束");
                                    if (qsjeDb > 0) {
                                        rblslxReal = rblslxErrorData;
                                        reson = "SQ事项申请单活动结束标识为是，请款金额为正数属于异常数据";
                                    } else {
                                        rblslxReal = rblslxEndData;
                                        reson = "";
                                    }
                                    log.info("rblslxReal:"+rblslxReal);
                                    DailyReportRelated.addDailyReportData(reportFormId, reportFormModeId, user, reportTableName, yxpthdsqm, actNm, actTotalAt, ptqdrq, jbr, zbdw, qsje, actTp, zjly, qsrq, sjly, nbsybl, bdh, rblslxReal, isConfirmDetail,reson,zjzhlx,hdjsbs);
                                }
                            } else {
                                rblslxReal = rblslxErrorData;
                                log.info("rblslxReal:"+rblslxReal);
                                reson = "找不到该授权码对应SQ事项申请单";
                                DailyReportRelated.addDailyReportData(reportFormId, reportFormModeId, user, reportTableName, yxpthdsqm, actNm, actTotalAt, ptqdrq, jbr, zbdw, qsje, actTp, zjly, qsrq, sjly, "0", "", rblslxReal, isConfirmDetail,reson,zjzhlx,hdjsbs);
                            }
                            // 修改明细表状态
                            ClearFundButtonRelated.updateStateByBillId(clearingFundDetailTableName, isConfirmDetail, billid);
                        } catch (Exception e) {
                            log.error("解析保存数据异常：" + e.getMessage());
                            throw new Exception("解析保存数据异常：" + e.getMessage());
                        }
                    } else {
                        log.error("查询营销活动事项台账表名为空！");
                        throw new Exception("查询营销活动事项台账表名为空！");
                    }
                } else {
                    log.error("授权码为空!");
                    if(result != null){
                        result += ","+"清算资金明细数据id:"+billid+"的营销平台活动授权码为空！";
                    }else {
                        result = "";
                        result += "清算资金明细数据id:"+billid+"的营销平台活动授权码为空！";
                    }
                }
            } else {
                // 按汇总规则已经【确认数据】写入《营销日报表台账》的明细数据，系统后台打上“已确认”标识，当用户重复操作汇总台账【确认数据】时提示“【业务类型+资金来源+清算日期+数据来源】该维度数据已确认”，此时系统控制不允许日报流水明细数据重复写入《营销日报表台账》。
                if(result != null){
                    result += ","+detailsTitle+"清算资金明细维度数据已确认";
                }else {
                    result = "";
                    result += detailsTitle+"清算资金明细维度数据已确认";
                }
            }
        }
        return result;
    }

}
